<template>
  <view class="coupon-container">
    <!-- Tabs切换 -->
    <view class="tabs-container">
      <view class="custom-tabs">
        <view class="tab-item" v-for="(tab, index) in tabsList" :key="index" :class="{ active: currentTab === index }" @click="changeTab(index)">
          <text class="tab-text">{{ tab.name }}</text>
          <view class="tab-indicator" v-if="currentTab === index"></view>
        </view>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <view class="coupon-item" v-for="(item, index) in couponList" :key="item.id">
        <view class="coupon-card">
          <view class="card-head">
            <view class="coupon-title">{{ item.name }}</view>
            <u-tag :text="item.status ? '开启' : '关闭'" :type="item.status ? 'success' : 'info'" size="mini" />
          </view>

          <view class="card-body">
            <view class="coupon-info">
              <!-- 折扣类型和金额 -->
              <view class="info-row" v-if="item.deductionBl > 0">
                <text class="label">折扣比例：</text>
                <text class="value price">{{ item.deductionBl }}折</text>
              </view>

              <view class="info-row" v-else>
                <text class="label">抵扣金额：</text>
                <text class="value price">¥{{ item.money }}</text>
              </view>

              <!-- 最低消费 -->
              <!--    <view class="info-row">
                <text class="label">最低消费：</text>
                <text class="value">¥{{ item.minPrice }}</text>
              </view> -->

              <!-- 使用时间 -->
              <view class="info-row">
                <text class="label">使用时间：</text>
                <text class="value">{{ formatDate(item.useStartTime) }} 至 {{ formatDate(item.useEndTime) }}</text>
              </view>

              <!-- 领取时间（如果是限时领取） -->
              <!--   <view class="info-row" v-if="!item.isForever">
                <text class="label">领取时间：</text>
                <text class="value">{{ formatDate(item.receiveStartTime) }} 至 {{ formatDate(item.receiveEndTime) }}</text>
              </view> -->

              <!-- 关联活动 -->
              <view class="info-row">
                <text class="label">关联活动：</text>
                <text class="value activity">{{ getActivityName(item.ebMerActivityId) }}</text>
              </view>

              <!-- 发放数量 -->
              <!--  <view class="info-row">
                <text class="label">发放数量：</text>
                <text class="value">{{ item.isLimited ? item.total + '张' : '不限量' }}</text>
              </view> -->

              <!-- 领取方式 -->
              <!--    <view class="info-row">
                <text class="label">领取方式：</text>
                <text class="value">{{ getCouponTypeText(item.type) }}</text>
              </view> -->

              <!-- 使用类型 -->
              <!--   <view class="info-row">
                <text class="label">使用类型：</text>
                <text class="value">{{ getUseTypeText(item.useType) }}</text>
              </view> -->

              <!-- 有效天数（如果不是固定时间） -->
              <!-- <view class="info-row" v-if="!item.isFixedTime && item.day">
                <text class="label">有效天数：</text>
                <text class="value">{{ item.day }}天</text>
              </view> -->
            </view>

            <view class="card-footer">
              <!-- 状态切换按钮 -->
              <u-button :type="item.status ? 'warning' : 'success'" size="mini" @click="toggleCouponStatus(item, index)">
                {{ item.status ? '下架' : '上架' }}
              </u-button>

              <!-- 删除按钮 -->
              <u-button type="error" size="mini" @click="deleteCoupon(item, index)">删除</u-button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && couponList.length === 0 && !hasData">
        <u-empty mode="coupon" text="暂无优惠券" />
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <u-loading-icon mode="circle" size="24" />
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 底部提示 -->
      <view class="end-tip" v-if="loadEnd && couponList.length > 0">
        <u-icon name="file-text" size="24" />
        <text class="end-text">没有更多数据了</text>
      </view>
    </view>

    <!-- 添加优惠券按钮 -->
    <view class="add-coupon-btn">
      <u-button type="primary" shape="circle" icon="plus" @click="addCoupon"> 添加优惠券 </u-button>
    </view>
  </view>
</template>

<script>
import { couponlist, activitylist, couponStatus, couponDel } from '../../utils/request_sh.js';

export default {
  data() {
    return {
      loading: false,
      loadEnd: false,
      hasData: false, // 是否有数据
      couponList: [],
      userInfo: {},
      page: 1,
      limit: 10,
      activityMap: new Map(), // 活动ID到名称的映射
      currentTab: 0, // 当前选中的tab 0:全部 1:上架 2:下架
      tabsList: [{ name: '全部' }, { name: '上架' }, { name: '下架' }]
    };
  },

  onLoad() {
    this.userInfo = uni.getStorageSync('userInfo');
    this.initData();
  },

  onShow() {
    this.initData();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData();
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore();
  },

  methods: {
    // 初始化数据
    initData() {
      this.page = 1;
      this.couponList = [];
      this.loadEnd = false;
      this.hasData = false;
      this.loadActivityMap();
      this.getCouponList();
    },

    // 刷新数据
    refreshData() {
      this.page = 1;
      this.couponList = [];
      this.loadEnd = false;
      this.hasData = false;
      this.getCouponList(() => {
        uni.stopPullDownRefresh();
      });
    },

    // 加载更多
    loadMore() {
      if (!this.loadEnd && !this.loading) {
        this.page++;
        this.getCouponList();
      }
    },

    // 切换tab
    changeTab(index) {
      this.currentTab = index;
      this.refreshData();
    },

    // 加载活动映射
    loadActivityMap() {
      if (!this.userInfo.merId) return;

      const params = {
        userRightComand: 'shanghuAdmin',
        pageNum: 1,
        pageSize: 100,
        ebMerId: this.userInfo.merId
      };

      activitylist(params)
        .then((res) => {
          const activities = res.rows || [];
          activities.forEach((activity) => {
            this.activityMap.set(activity.id, activity.name);
          });
        })
        .catch((err) => {
          console.error('获取活动列表失败:', err);
        });
    },

    // 获取优惠券列表
    getCouponList(callback) {
      if (this.loadEnd || this.loading) return;

      this.loading = true;

      // 构造请求参数
      const params = {
        page: this.page,
        limit: this.limit,
        ebMerId: this.userInfo.merId
      };

      // 根据tab筛选状态
      if (this.currentTab === 1) {
        // 上架
        params.status = true;
      } else if (this.currentTab === 2) {
        // 下架
        params.status = false;
      }

      couponlist(params)
        .then((res) => {
          const list = res.data.list || [];
          const total = res.total || 0;

          // 判断是否加载完所有数据
          this.loadEnd = list.length < this.limit;
          this.hasData = this.hasData || list.length > 0;

          // 合并数据
          if (this.page === 1) {
            this.couponList = list;
          } else {
            this.couponList = this.couponList.concat(list);
          }

          this.loading = false;

          if (callback && typeof callback === 'function') {
            callback();
          }
        })
        .catch((err) => {
          console.error('获取优惠券列表失败:', err);
          this.loading = false;
          this.loadEnd = true;

          uni.showToast({
            title: '数据加载失败',
            icon: 'none'
          });

          if (callback && typeof callback === 'function') {
            callback();
          }
        });
    },

    // 获取优惠券类型文本
    getCouponTypeText(type) {
      const typeMap = {
        1: '手动领取',
        2: '新人券',
        3: '赠送券'
      };
      return typeMap[type] || '未知';
    },

    // 获取使用类型文本
    getUseTypeText(useType) {
      const useTypeMap = {
        1: '全场通用',
        2: '商品券',
        3: '品类券'
      };
      return useTypeMap[useType] || '未知';
    },

    // 获取活动名称
    getActivityName(activityId) {
      return this.activityMap.get(activityId) || '未知活动';
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '无';

      try {
        // 如果是时间戳格式，转换为日期
        if (typeof dateStr === 'number') {
          const date = new Date(dateStr);
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          return `${year}-${month}-${day}`;
        }

        // 如果是字符串格式，直接返回（假设已经是 yyyy-MM-dd 格式）
        if (typeof dateStr === 'string') {
          return dateStr;
        }

        return '无';
      } catch (e) {
        console.error('日期格式化错误:', e);
        return '无效日期';
      }
    },

    // 添加优惠券
    addCoupon() {
      uni.navigateTo({
        url: '/pages_sh/myCenter/couponEdit'
      });
    },

    // 切换优惠券状态（上架/下架）
    toggleCouponStatus(coupon, index) {
      const newStatus = !coupon.status;

      uni.showModal({
        title: '确认操作',
        content: `确定要${newStatus ? '上架' : '下架'}"${coupon.name}"这张优惠券吗？`,
        success: (res) => {
          if (res.confirm) {
            const params = {
              id: coupon.id,
              status: newStatus
            };

            couponStatus(params)
              .then(() => {
                // 根据当前tab决定如何刷新数据
                if (this.currentTab === 0) {
                  // 全部tab，直接更新本地数据
                  this.couponList[index].status = newStatus;
                } else {
                  // 上架或下架tab，重新加载数据
                  this.refreshData();
                }

                uni.showToast({
                  title: `${newStatus ? '上架' : '下架'}成功`,
                  icon: 'success'
                });
              })
              .catch((err) => {
                console.error('状态切换失败:', err);
                uni.showToast({
                  title: '操作失败',
                  icon: 'none'
                });
              });
          }
        }
      });
    },

    // 删除优惠券
    deleteCoupon(coupon, index) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除"${coupon.name}"这张优惠券吗？`,
        success: (res) => {
          if (res.confirm) {
            const params = {
              id: coupon.id
            };

            couponDel(params)
              .then(() => {
                // 根据当前tab决定如何刷新数据
                if (this.currentTab === 0) {
                  // 全部tab，直接从列表中移除
                  this.couponList.splice(index, 1);
                } else {
                  // 上架或下架tab，重新加载数据
                  this.refreshData();
                }

                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
              })
              .catch((err) => {
                console.error('删除失败:', err);
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.coupon-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  box-sizing: border-box;
  padding-bottom: 120rpx;
}

.page-header {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .page-subtitle {
    font-size: 28rpx;
    color: #999;
  }
}

.tabs-container {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  padding: 0 20rpx;
}

.custom-tabs {
  display: flex;
  height: 80rpx;
  position: relative;

  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;

    .tab-text {
      font-size: 28rpx;
      color: #666;
    }

    &.active {
      .tab-text {
        color: #2979ff;
        font-weight: bold;
      }
    }

    .tab-indicator {
      position: absolute;
      bottom: 0;
      width: 60rpx;
      height: 6rpx;
      background-color: #2979ff;
      border-radius: 3rpx;
    }
  }
}

.coupon-item {
  margin-bottom: 20rpx;
}

.coupon-card {
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .coupon-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.card-body {
  padding: 20rpx;

  .coupon-info {
    .info-row {
      display: flex;
      margin-bottom: 15rpx;

      .label {
        font-size: 28rpx;
        color: #666;
        width: 180rpx;
      }

      .value {
        font-size: 28rpx;
        color: #333;
        flex: 1;

        &.price {
          font-weight: bold;
          color: #e93323;
        }

        &.activity {
          color: #2979ff;
        }
      }
    }
  }

  .card-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;

    .u-button {
      margin-left: 20rpx;
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;

  .loading-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #999;
  }
}

.end-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;

  .end-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #999;
  }
}

.add-coupon-btn {
  position: fixed;
  bottom: 60rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  z-index: 999;
}
</style>
